package com.mcxx.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

public class ReflectUtil {



    public static void setFieldValueByFieldName(String fieldName, Object object,String value) {

        if(isExistField(fieldName,object)){
            try {
                Field field = object.getClass().getDeclaredField(fieldName);

                field.setAccessible(true);
                field.set(object,value);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }


    }


    public static String getFieldValueByFieldName(String fieldName, Object object) {

        if(!isExistField(fieldName,object)){
            return null;
        }
        try {
            Field field = null;
            if(UserAccountVo.class.equals(object.getClass())){
                field = object.getClass().getSuperclass().getDeclaredField(fieldName);
            }else{
                field = object.getClass().getDeclaredField(fieldName);
            }


            field.setAccessible(true);
            Object hisValue = field.get(object);

            if (null == hisValue) {
                return null;
            }

            String value = "";
            String type = field.getType().toString();
            if (type.contains("String")) {
                value = hisValue.toString();
            }else if (type.contains("String")) {
                value = hisValue.toString();
            }

            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }



    public static Boolean isExistField(String field, Object obj) {
        if (obj == null || StringUtils.isEmpty(field)) {
            return null;
        }
        Object o = JSON.toJSON(obj);
        JSONObject jsonObj = new JSONObject();
        if (o instanceof JSONObject) {
            jsonObj = (JSONObject) o;
        }
        return jsonObj.containsKey(field);
    }

    public static Field[] getObjectFields(Object obj) {
        return obj.getClass().getDeclaredFields();
    }

    public static Class getObjectClass(Object obj) {
        return obj.getClass();
    }
}
